/**
 * Copyright (C) 2009-2012, KingHool.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses.
 */
package com.kinghool.smodel.io;

import java.util.List;

import com.kinghool.ebos.commons.utils.Utils;
import com.kinghool.smodel.IModel;
import com.kinghool.smodel.def.ModelDefinition;
import com.kinghool.smodel.listener.IModelLoadListener;
import com.kinghool.smodel.listener.ModelLoadStatusEvent;

/**
 * 
 * @Author Allen Deng(dengtailin@gmail.com) 
 */
public class ModelLoader<E extends IModel> { 
    protected IModelSource<E> modelSource;
    protected volatile boolean isModelLoaded = false;
    protected List<IModelLoadListener> listeners = Utils.newList();
	   
	public ModelLoader(IModelSource<E> modelSource) {
		this.modelSource = modelSource;
	}   
	
	public E load() {
		return load(null);
	}  
	
	public E load(ModelDefinition modelDefinition) {
		isModelLoaded = false;
		fireDocLoadStatusEvent(ModelLoadStatusEvent.LOADING);
		E model = null;
		try {
			model = modelSource.load(modelDefinition);
	        isModelLoaded = model.isValid(); 
		} finally {
			if (isModelLoaded) {
				fireDocLoadStatusEvent(ModelLoadStatusEvent.READY);		 		
			} else {
				fireDocLoadStatusEvent(ModelLoadStatusEvent.FAIL);	  	
			} 
		} 
		return model;
	}  
	
	public void flush(E model) {
		modelSource.flush(model);
	}   
	
	public boolean isDocLoaded() { 
		return isModelLoaded;
	}

	public void addXmlDocLoadListener(IModelLoadListener listener) {
		listeners.add(listener);
	}

	public void removeXmlDocLoadListener(IModelLoadListener listener) {
		listeners.remove(listener); 		
	}  

	public void setModelSource(IModelSource<E> modelSource) {
		this.modelSource = modelSource;
	}
	 
	protected void fireDocLoadStatusEvent(ModelLoadStatusEvent event) {
		for (IModelLoadListener listener : listeners) {
			listener.loadStatusChange(event);
		}
	}
}
